package com.study.sparsearray;

/**
 * 稀疏数组的转换和解析
 */

public class SparseArray {
    public static void main(String[] args) {
        // 1.先创建一个原始的二维数组
        int array1[][] = new int[11][11];
        array1[1][2] = 1;
        array1[2][3] = 2;
        for (int[] row :array1){
            for (int data : row){
                System.out.printf("%d\t" ,data);
            }
            System.out.println();
        }
        // 统计二维数组中的不同元素的个数
        int sum  = 0;
        for (int[] row :array1){
            for (int data : row){
                if (data!=0){
                    sum++;
                }
            }
        }
        //根据sum创建稀疏数组
        int sparseArray[][] = new int[sum+1][3];
        sparseArray[0][0] = 11;
        sparseArray[0][1] = 11;
        sparseArray[0][2] = sum;
        // 将二维数组转化为稀疏数组
        int sparseRowNumber = 1;
        int arrayRowNumber = 0;
            for (int [] row: array1){
                for (int j = 0; j <row.length ; j++) {
                    if (array1[arrayRowNumber][j]!=0){
                        sparseArray[sparseRowNumber][0] = arrayRowNumber;
                        sparseArray[sparseRowNumber][1] = j;
                        sparseArray[sparseRowNumber][2] = array1[arrayRowNumber][j];
                        sparseRowNumber++;
                    }
                }
                arrayRowNumber++;
            }
            for (int [] row : sparseArray){
                for (int data : row){
                    System.out.printf("%d\t", data);
                }
                System.out.println();
            }
            // 将而稀疏数组重新转换为二维数组
        int arr2[][] = new int[sparseArray[0][0]][sparseArray[0][1]];
        for (int i = 1; i < sparseArray.length; i++) {
            arr2[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
        }
        System.out.println("解析稀疏数组的结果");
        for (int[] row :arr2){
            for (int data : row){
                System.out.printf("%d\t" ,data);
            }
            System.out.println();
        }

    }
}
